package com.cjst.controller.api.sys;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.cjst.util.json.ResultObj;

//@Controller
//@RequestMapping("/upload")
public class UploadController {

	private Logger log = Logger.getLogger(UploadController.class);

	@Value("${img.location}")
	private String fileUploadPath;
	@Value("${file.path}")
	private String filePath;

	/**
	 * 上传头像
	 * 
	 * @param request
	 * @param file
	 * @return
	 */
	@RequestMapping("/uploadSingleFile")
	@ResponseBody
	@Transactional
	public Object uploadSingleFile(HttpServletRequest request, MultipartFile file, String dirs) {
		try {

			// 文件上传路径
			String serverPath = fileUploadPath;

			String uploadDir = "";

			// 文件名称
			String fileName = file.getOriginalFilename();
			// 文件后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (dirs != null && dirs.length() > 0) {
				uploadDir = uploadDir + "/" + dirs + "/" + "avator";
			} else {
				uploadDir = uploadDir + "/" + "avator";
			}

			// 检查目录是否存在
			File dir = new File(serverPath + uploadDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 随机名称
			String randomFileName = UUID.randomUUID().toString();
			// 文件存在服务器上的路径
			String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

			// 将文件上传到文集的物理地址
			File serverFile = new File(serverPath + fileUrl);
			file.transferTo(serverFile);
			log.info("文件上传成功");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("fileUrl", fileUrl);
			map.put("filePath", filePath + fileUrl);
			return new ResultObj(1, "文件上传成功", map);

		} catch (Exception e) {
			log.error(e.getMessage());
			return new ResultObj(0, e.getMessage(), null);
		}

	}

	public Object uploadMultiFile(HttpServletRequest request, MultipartFile file, String dirs) {

		return null;
	}

	@RequestMapping("/uploadSingleImage")
	@ResponseBody
	@Transactional
	public Object uploadSingleImage(HttpServletRequest request, MultipartFile file, String dirs) {
		try {

			// 文件上传路径
			String serverPath = fileUploadPath;

			String uploadDir = "";

			// 文件名称
			String fileName = file.getOriginalFilename();
			// 文件后缀
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			if (dirs != null && dirs.length() > 0) {
				uploadDir = uploadDir + "/" + dirs + "/" + "avator";
			} else {
				uploadDir = uploadDir + "/" + "avator";
			}

			// 检查目录是否存在
			File dir = new File(serverPath + uploadDir);
			if (!dir.exists()) {
				dir.mkdirs();
			}
			// 随机名称
			String randomFileName = UUID.randomUUID().toString();
			// 文件存在服务器上的路径
			String fileUrl = uploadDir + "/" + randomFileName + "." + suffix;

			// 将文件上传到文集的物理地址
			File serverFile = new File(serverPath + fileUrl);
			file.transferTo(serverFile);
			log.info("文件上传成功");
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("fileUrl", fileUrl);
			map.put("filePath", filePath + fileUrl);
			return new ResultObj(1, "文件上传成功", map);

		} catch (Exception e) {
			log.error(e.getMessage());
			return new ResultObj(0, e.getMessage(), null);
		}
	}

	public Object uploadMultiImage(HttpServletRequest request) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	        if(fileMap == null || fileMap.size() == 0){
	            return new ResultObj(0,"请上传文件,注意文件的name属性为file",0);
	        }
	        Collection<MultipartFile> files = fileMap.values();
	        for(MultipartFile file:files){
	        /**
	        注意这里获取的个数，是根据前端form表单里有几个，type=file来决定的，
	        比如你虽然只点选了一个文件，上传，但这里实际上回有两个MultipartFile对 象，只不过其中一个MutipartFile的文件名会为空，这就是为什么下边会有个判断文件名
	        为空的步骤**/
	            String req= file.getOriginalFilename();
	            if(StringUtils.isEmpty(req)){
	                continue;
	            }
	            File tempFile = getTmpFile(req);
	            System.out.println(tempFile.getAbsolutePath());
	            if(!tempFile.exists()){
	                tempFile.getParentFile().mkdirs();
	                try {
	                    tempFile.createNewFile();
	                    file.transferTo(tempFile); //到这里tempFile即是上传上来的文件。
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            System.out.println(req);
	        }

		return null;
	}
	
	public Object uploadMultiFile(HttpServletRequest request) {
		 MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		 
		 Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
	        if(fileMap == null || fileMap.size() == 0){
	            return new ResultObj(0,"请上传文件,注意文件的name属性为file",0);
	        }
	        Collection<MultipartFile> files = fileMap.values();
	        for(MultipartFile file:files){
	        /**
	        注意这里获取的个数，是根据前端form表单里有几个，type=file来决定的，
	        比如你虽然只点选了一个文件，上传，但这里实际上回有两个MultipartFile对 象，只不过其中一个MutipartFile的文件名会为空，这就是为什么下边会有个判断文件名
	        为空的步骤**/
	            String req= file.getOriginalFilename();
	            if(StringUtils.isEmpty(req)){
	                continue;
	            }
	            File tempFile = getTmpFile(req);
	            System.out.println(tempFile.getAbsolutePath());
	            if(!tempFile.exists()){
	                tempFile.getParentFile().mkdirs();
	                try {
	                    tempFile.createNewFile();
	                    file.transferTo(tempFile); //到这里tempFile即是上传上来的文件。
	                } catch (IOException e) {
	                    e.printStackTrace();
	                }
	            }
	            System.out.println(req);
	        }

		return null;
	}
	
	private File getTmpFile(String fileName) {
		File tmpDir = FileUtils.getTempDirectory();
		System.out.println("========"+tmpDir.getAbsolutePath());
		String tmpFileName = (Math.random() * 10000 + "").replace(".", "")+"_"+fileName;
		return new File(tmpDir, tmpFileName);
	}

}
